package com.codeplatform.util;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 彩色日志工具类
 * 提供带颜色和高亮效果的日志输出功能
 */
@Slf4j
@Component
public class ColorLogger {

    // ANSI颜色代码
    public static final String RESET = "\u001B[0m";
    public static final String BLACK = "\u001B[30m";
    public static final String RED = "\u001B[31m";
    public static final String GREEN = "\u001B[32m";
    public static final String YELLOW = "\u001B[33m";
    public static final String BLUE = "\u001B[34m";
    public static final String PURPLE = "\u001B[35m";
    public static final String CYAN = "\u001B[36m";
    public static final String WHITE = "\u001B[37m";
    
    // 背景颜色
    public static final String BLACK_BACKGROUND = "\u001B[40m";
    public static final String RED_BACKGROUND = "\u001B[41m";
    public static final String GREEN_BACKGROUND = "\u001B[42m";
    public static final String YELLOW_BACKGROUND = "\u001B[43m";
    public static final String BLUE_BACKGROUND = "\u001B[44m";
    public static final String PURPLE_BACKGROUND = "\u001B[45m";
    public static final String CYAN_BACKGROUND = "\u001B[46m";
    public static final String WHITE_BACKGROUND = "\u001B[47m";
    
    // 文本样式
    public static final String BOLD = "\u001B[1m";
    public static final String UNDERLINE = "\u001B[4m";
    public static final String ITALIC = "\u001B[3m";
    public static final String STRIKETHROUGH = "\u001B[9m";
    
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    
    /**
     * 输出成功信息（绿色）
     */
    public static void success(String message, Object... args) {
        String formattedMessage = formatMessage(message, args);
        log.info(GREEN + "✓ " + formattedMessage + RESET);
    }
    
    /**
     * 输出警告信息（黄色）
     */
    public static void warning(String message, Object... args) {
        String formattedMessage = formatMessage(message, args);
        log.warn(YELLOW + "⚠ " + formattedMessage + RESET);
    }
    
    /**
     * 输出错误信息（红色）
     */
    public static void error(String message, Object... args) {
        String formattedMessage = formatMessage(message, args);
        log.error(RED + "✗ " + formattedMessage + RESET);
    }
    
    /**
     * 输出错误信息（红色）带异常
     */
    public static void error(String message, Throwable throwable, Object... args) {
        String formattedMessage = formatMessage(message, args);
        log.error(RED + "✗ " + formattedMessage + RESET, throwable);
    }
    
    /**
     * 输出信息（蓝色）
     */
    public static void info(String message, Object... args) {
        String formattedMessage = formatMessage(message, args);
        log.info(BLUE + "ℹ " + formattedMessage + RESET);
    }
    
    /**
     * 输出调试信息（紫色）
     */
    public static void debug(String message, Object... args) {
        String formattedMessage = formatMessage(message, args);
        log.debug(PURPLE + "🔍 " + formattedMessage + RESET);
    }
    
    /**
     * 输出API请求日志（青色）
     */
    public static void apiRequest(String method, String url, String requestId) {
        MDC.put("requestId", requestId);
        String message = String.format("API请求: %s %s [请求ID: %s]", method, url, requestId);
        log.info(CYAN + "🌐 " + message + RESET);
    }
    
    /**
     * 输出API响应日志（青色）
     */
    public static void apiResponse(String method, String url, int statusCode, long duration, String requestId) {
        MDC.put("requestId", requestId);
        String statusColor = getStatusColor(statusCode);
        String message = String.format("API响应: %s %s [状态: %s%d%s] [耗时: %dms] [请求ID: %s]", 
                method, url, statusColor, statusCode, RESET + CYAN, duration, requestId);
        log.info(CYAN + "📤 " + message + RESET);
        MDC.remove("requestId");
    }
    
    /**
     * 输出数据库操作日志（绿色）
     */
    public static void database(String operation, String table, long duration) {
        String message = String.format("数据库操作: %s [表: %s] [耗时: %dms]", operation, table, duration);
        log.debug(GREEN + "🗄 " + message + RESET);
    }
    
    /**
     * 输出安全相关日志（红色背景）
     */
    public static void security(String event, String user, String details) {
        String message = String.format("安全事件: %s [用户: %s] [详情: %s]", event, user, details);
        log.warn(RED_BACKGROUND + WHITE + "🔒 " + message + RESET);
    }
    
    /**
     * 输出性能监控日志（黄色）
     */
    public static void performance(String operation, long duration, String details) {
        String message = String.format("性能监控: %s [耗时: %dms] [详情: %s]", operation, duration, details);
        String color = duration > 1000 ? RED : (duration > 500 ? YELLOW : GREEN);
        log.info(color + "⚡ " + message + RESET);
    }
    
    /**
     * 输出业务日志（默认颜色）
     */
    public static void business(String event, String details, Object... args) {
        String formattedDetails = formatMessage(details, args);
        String message = String.format("业务事件: %s [详情: %s]", event, formattedDetails);
        log.info(BOLD + "📋 " + message + RESET);
    }
    
    /**
     * 输出系统启动日志（绿色背景）
     */
    public static void startup(String component, String status) {
        String message = String.format("系统启动: %s [状态: %s]", component, status);
        log.info(GREEN_BACKGROUND + BLACK + "🚀 " + message + RESET);
    }
    
    /**
     * 输出系统关闭日志（红色背景）
     */
    public static void shutdown(String component, String reason) {
        String message = String.format("系统关闭: %s [原因: %s]", component, reason);
        log.info(RED_BACKGROUND + WHITE + "🛑 " + message + RESET);
    }
    
    /**
     * 高亮显示关键信息
     */
    public static String highlight(String text) {
        return BOLD + YELLOW_BACKGROUND + BLACK + text + RESET;
    }
    
    /**
     * 高亮显示错误信息
     */
    public static String highlightError(String text) {
        return BOLD + RED_BACKGROUND + WHITE + text + RESET;
    }
    
    /**
     * 高亮显示成功信息
     */
    public static String highlightSuccess(String text) {
        return BOLD + GREEN_BACKGROUND + BLACK + text + RESET;
    }
    
    /**
     * 生成请求ID
     */
    public static String generateRequestId() {
        return UUID.randomUUID().toString().substring(0, 8);
    }
    
    /**
     * 格式化消息
     */
    private static String formatMessage(String message, Object... args) {
        if (args.length == 0) {
            return message;
        }
        try {
            return String.format(message, args);
        } catch (Exception e) {
            return message + " [格式化参数错误: " + e.getMessage() + "]";
        }
    }
    
    /**
     * 根据HTTP状态码获取颜色
     */
    private static String getStatusColor(int statusCode) {
        if (statusCode >= 200 && statusCode < 300) {
            return GREEN;
        } else if (statusCode >= 300 && statusCode < 400) {
            return YELLOW;
        } else if (statusCode >= 400 && statusCode < 500) {
            return RED;
        } else if (statusCode >= 500) {
            return RED_BACKGROUND + WHITE;
        }
        return RESET;
    }
    
    /**
     * 创建分隔线（无色带版本）
     */
    public static void separator(String title) {
        String line = "=" + "=".repeat(50) + "=";
        log.info(line);
        if (title != null && !title.trim().isEmpty()) {
            String centeredTitle = String.format("%-25s %s %-25s", "", title.trim(), "");
            log.info(centeredTitle);
            log.info(line);
        }
    }
    
    /**
     * 输出表格头部
     */
    public static void tableHeader(String... headers) {
        StringBuilder sb = new StringBuilder();
        sb.append(BOLD).append(BLUE_BACKGROUND).append(WHITE);
        for (String header : headers) {
            sb.append(String.format("%-20s", header));
        }
        sb.append(RESET);
        log.info(sb.toString());
    }
    
    /**
     * 输出表格行
     */
    public static void tableRow(String... values) {
        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            sb.append(String.format("%-20s", value));
        }
        log.info(sb.toString());
    }
}